const express=require('express')
const config=require('../../config')
const NotesModel=require('../models/notes')
const UsersModel=require('../models/users')
const constant=require('../constant')
const db=require('../models/database')

let router=express.Router()

router.get('/list',async function(req,res,next){
    if(await UsersModel.IsRightToken(JSON.parse(req.cookies.user).token,JSON.parse(req.cookies.user).id)){
        res.render('note/list',{site:config.site,title:'剪贴板列表',list:await NotesModel.GetNoteList(JSON.parse(req.cookies.user).id)})
    }else{
        res.redirect(303,'/user/login')
    }
});

router.get('/read/:id',async function(req,res,next){
    NotesModel.GetContent(req.params.id).then(
        (ans)=>{
            res.render('note/read',{
                site:config.site,
                title:"剪贴板:"+ans.title,
                data:ans})
        })
    .catch(
        (err)=>{
            if(err==constant.ERR_NONEXISTENT_NOTE){
                res.render('note/read',{
                    site:config.site,
                    title:"不存在的剪贴板",
                    data:{
                        title:"不存在的剪贴板",
                        content:"您可能输入了错误的 URL , 或此剪贴板已被删除"
                    }})
            }else{
                throw err
            }
        })
});

router.get('/new',async function(req,res,next){
    res.render('note/new',{site:config.site,title:'新剪贴板'})
});

router.post('/new',async function(req,res,next){
    NotesModel.UpdateNote(await NotesModel.CreateNote(JSON.parse(req.cookies.user).id,req.body.title),req.body.title,req.body.content)
    res.end()
});

module.exports=router;